<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ArrayToEntityConverter
 *
 * @author JeyDotC
 */
class ArrayToEntityConverter {

    function convert(array &$array, &$targetObject, array &$mapping = array()) {

        foreach ($array as $propertyName => &$propertyValue) {
            if (is_scalar($propertyValue)) {
                $this->invokeSet($propertyName, $propertyValue, $targetObject);
            } else {
                //Determinar si existe una clase para este objeto compuesto.
                if (array_key_exists($propertyName, $mapping)) {

                    $InnerClassName = $mapping[$propertyName];
                    $innerMapping = array();
                    //Determine if there is any internal mapping for the inner object.
                    if (array_key_exists($propertyName . ".mapping", $mapping)) {
                        $innerMapping = $mapping[$propertyName . ".mapping"];
                    }

                    if ($array[$propertyName] != null) {
                        $newobject = new $InnerClassName();
                        $this->convert($array[$propertyName], $newobject, $innerMapping);
                        $this->invokeSet($propertyName, $newobject, $targetObject);
                    }
                } else if (array_key_exists("$propertyName.array", $mapping) && is_array($propertyValue)) {
                    $InnerClassName = $mapping["$propertyName.array"];
                    $innerMapping = array();
                    //Determine if there is any internal mapping for the inner object.
                    if (array_key_exists("$propertyName.array.mapping", $mapping)) {
                        $innerMapping = $mapping["$propertyName.array.mapping"];
                    }

                    $list = array();
                    foreach ($propertyValue as &$object) {
                        if ($object != null) {
                            $newobject = new $InnerClassName();
                            $this->convert($object, $newobject, $innerMapping);
                            array_push($list, $newobject);
                        }
                    }

                    $this->invokeSet($propertyName, $list, $targetObject);
                }
            }

            $array[$propertyName] = null;
            unset($array[$propertyName]);
        }
    }

    private function invokeSet($propertyName, &$propertyValue, &$targetObject) {
        
        $setProperty = "set$propertyName";
        
        if (method_exists($targetObject, $method)) {
            $targetObject->$setProperty($propertyValue);
        } else if(property_exists($targetObject, $propertyName)) {
            $targetObject->$propertyName = $propertyValue;
        }
    }

}

?>
